<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 极速
 */
class JisuController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.ordNo") ? I("request.ordNo") : I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        // $isMobile = isMobile();
        $return = $this->orderadd( $parameter );

        switch($this->config['paytype']){
            case 1:
                $pay_bankcode = 'WEIXIN_CODE';
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }


        $arr_data = [
            'mer_id' => $this->config['mch_id'], //商户id
            'timestamp' => date('Y-m-d H:i:s'), //订单时间
            'terminal' => $pay_bankcode,  //渠道类型：PC-网关  H5-快捷  ALI_CODE-支付宝扫码 ALI_PAY_WAP-支付宝H5  WEIXIN_CODE-微信扫码  WEIXIN_PAY_WAP-微信H5
            'version' => '01', //版本
            'amount' => intval($return['amount']*100), //收款金额 以 ‘分’ 为单位
            'backurl' => $return['callbackurl'],  //支付成功同步回调地址
            'failUrl' => $return['callbackurl'],  //支付失败同步回调地址
            'ServerUrl' => $return['notifyurl'], //成功支付异步回调地址
            'businessnumber' => $return['orderid'], //订单号 必须以数字或者字母组合，长度必须30位 保证不重复
            'goodsName' => '测试名字呢', //商品名称
            'IsCredit' => 0,  //可空 直连必填(0:非直联 1：直联)
            'BankCode' =>'',  //可空 直连必填(IPS 唯一标识指定支付银行的编号)
            'ProductType' => '',//可空 直连必填(1个人网银 2企业网银)
            'UserId' => '',//可空 商户客户唯一标识id
            'UserRealName' => '',//可空 付款人姓名
            'UserRealMobile' => '',//可空 付款人手机号
            'UserRealBankCard' => '',//可空 付款人银行卡号
            'UserRealIdNumber' => '',//可空 付款人身份证号
        ];

        //生成签名
        $arr_data['sign'] = $this->_getSign($arr_data,$this->config['signkey']);
        //生签以md5方式 加密
        $arr_data['sign_type'] = 'md5';

        $res = curl_json($this->config['gateway'], $arr_data); //json提交

        $resp = json_decode($res,true);

        $code = $resp['data']['trade_qrcode'];

        if(!$code){
            if($resp['msg']){
                $this->showmessage($resp['msg'],['code'=>C("THIRDCODES.".$this->class)]);
            }

            $this->showmessage('获取支付连接失败！',['code'=>C("THIRDCODES.".$this->class)]);
        }

        header("Location: {$code}");
    }

    /**
     * 生成签名
     * @param array $param
     * @param string $app_secret
     * @return string
     */
    public  function _getSign(array $arr_param,$secret_key)
    {
        // sign,sign_type不参与签名
        unset($arr_param['sign'], $arr_param['sign_type']);

        ksort($arr_param);//根据键值升序排列

        $str_sign = '';

        foreach ($arr_param as $key => $value) {
            $str_sign .= $key . '=' . $value . '&';
        }

        $str_sign .= $secret_key;

        return strtoupper(md5($str_sign));
    }

    //通知
    public function notifyurl(){
        //$this->debug_callback();

        //IP白名单
        if(!$this->checkip(getIP(),['47.107.147.158','120.77.47.7'])){
            exit("wrong");
        }
        $p = I("post.");

        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['businessnumber'];

        //获取订单
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据

        if($p['opstate'] === '0'){
            M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

                "pay_orderid_rd"=>0,
                "pay_true"=>$p['amount'],
            ));
        }else{
            M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

                "pay_orderid_rd"=>0,
            ));
        }

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        $sign = $p['sign'];
        unset($p['sign']);
        unset($p['sign_type']);

        //生成签名
        $sign2 = $this->_getSign($p,$this->config['signkey']);

        if($sign !== $sign2){
            exit("sign_wrong");
        }

        if($p['status'] !== '成功'){
            exit("pay_fail");
        }

        $this->async($find['pay_orderid'],"success");
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}
